// pages/report/report.js
var app = getApp();
//引入echarts(注意不是ec-canvas/ec-canvas，而是ec-canvas/echarts)
import * as echarts from "../../ec-canvas/echarts";

//血糖图表
let sugarChart;
let sugarChartData = [{
        'value': 0,
        'name': '正常',
    },
    {
        'value': 0,
        'name': '偏高'
    },
    {
        'value': 0,
        'name': '偏低'
    }
]
let sugarChartOption = {
    tooltip: {
        show: false,
        trigger: 'item',
        formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
        orient: 'vertical',
        left: '75%', //图例距离左的距离
        y: 'center', //图例上下居中
    },
    color: ['#00D868', '#F19696', '#ffca28'],
    series: [{
        name: '血糖',
        type: 'pie',
        center: ["38%", "50%"], // 饼图左右、上下位置
        radius: ['42.87%', '0.00%'], //外径、内径
        avoidLabelOverlap: true,
        itemStyle: {
            borderRadius: [0, 0, 5, 5],
            borderColor: '#fff',
            borderWidth: 2
        },
        label: {
            show: true,
            position: 'inside',
            fontSize: 12,
            fontWeight: 'bold',
            color: '#fff',
            formatter: "{d}%",
        },
        labelLayout: {
            verticalAlign: "center",

        },
        emphasis: {
            scale: false, //是否开启选中放大
            label: {
                show: true,
            },
        },
        data: sugarChartData
    }]
}

function initSugarChart(canvas, width, height, dpr) {
    sugarChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    canvas.setChart(sugarChart);
    sugarChart.setOption(sugarChartOption);
    return sugarChart;
}

//饮食图表
let foodChart;
let foodChartData = {
    date: ['12', '13', '14', '15', '16', '17', '18'],
    protein: [0, 0, 0, 0, 20, 0, 5], //蛋白质
    cbd: [10, 10, 10, 10, 25, 0, 6], //碳水
    fat: [5, 5, 5, 5, 20, 30, 60], //脂肪


}
let foodChartOption = {

    grid: {
        //  left: '20%', //距离左侧边距
        //  right: '0%',
        //  top: '10%',
        //  bottom:'25%',
        containLabel: false
    },
    legend: {
        orient: 'horizontal',
        // left: '75%', //图例距离左的距离
        x: 'center', //可设定图例在左、右、居中
        y: 'bottom', //可设定图例在上、下、居中
    },
    dataZoom: [{
        type: 'inside', //1平移 缩放
        throttle: '50', //设置触发视图刷新的频率。单位为毫秒（ms）。
        minValueSpan: 5, //用于限制窗口大小的最小值,在类目轴上可以设置为 5 表示 5 个类目
        start: 1, //数据窗口范围的起始百分比 范围是：0 ~ 100。表示 0% ~ 100%。
        end: 10, //数据窗口范围的结束百分比。范围是：0 ~ 100。
        zoomLock: true, //如果设置为 true 则锁定选择区域的大小，也就是说，只能平移，不能缩放。
    }],
    color: ['#F9F06F', '#F19696', '#00D868'],
    tooltip: {
        trigger: 'item', // 触发类型，可选值: 'item'（数据项触发），'axis'（坐标轴触发），'none'（不触发）
        axisPointer: {
            type: 'line', // 设置触发提示的指示器类型 
            // 可选值: 'line'（直线指示器），'shadow'（阴影指示器），'cross'（十字准星指示器）
        },
        backgroundColor: 'rgba(0,47,54,1)', // 设置背景颜色
        textStyle: {
            color: '#fff', // 设置文本颜色
            fontSize: 12, // 设置文字大小

        },
        padding: [5, 10], // 内边距
        //  formatter: `2023年{b}<br/>US$ {c}`, 
    },


    xAxis: {
        type: 'category',
        data: foodChartData.date,
        axisLine: {
            onZero: true
        },
        axisTick: {
            show: true,
            inside: true //刻度内置
        },
        splitLine: { //网格线
            show: true
        },
    },
    yAxis: {
        type: 'value',
        axisLine: {
            show: true,
            onZero: true,
            symbol: ['none', 'arrow'],
            symbolSize: [5, 10],
            symbolOffset: [0, 8]
        },

    },
    series: [{
            name: "蛋白质",
            data: foodChartData.protein,
            type: 'line',
            smooth: false, //
        },
        {
            name: "碳水",
            data: foodChartData.cbd,
            type: 'line',
            smooth: false, //
        },
        {
            name: "脂肪",
            data: foodChartData.fat,
            type: 'line',
            smooth: false, //
        }
    ]
};

function initFoodChart(canvas, width, height, dpr) {
    foodChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    canvas.setChart(foodChart);
    foodChart.setOption(foodChartOption);
    return foodChart;
}


// 运动图表
let sportChart;
let sportChartData = {
    date: ['12', '13', '14', '15', '16', '17', '18'],
    value: [10, 22, 15, 15, 9, 16, 20]
}

let sportChartOption = {
    xAxis: {
        data: sportChartData.date
    },
    yAxis: {
        name: "每日平均心率（单位: bpm）",
        nameTextStyle: {
            align: 'left',
            fontSize: 16
        },
        splitLine: {
            show: true,
            lineStyle: {
                type: 'dashed'
            }
        }
    },
    series: [{
        type: 'bar',
        data: sportChartData.value,
        itemStyle: {
            color: '#00976B',
            // barBorderRadius: 5,
            // borderWidth: 1,
            // borderType: 'solid',
            // borderColor: '#73c0de',
            // shadowColor: '#5470c6',
            // shadowBlur: 3,
            barBorderRadius: [30, 30, 0, 0]
        }
    }]
}

function initSportChart(canvas, width, height, dpr) {
    sportChart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
    });
    canvas.setChart(sportChart);
    sportChart.setOption(sportChartOption);
    return sportChart;
}


Page({

    /**
     * 页面的初始数据
     */
    data: {
        timeData: {
            year: '2024年',
            month: '1月',
            dates: ['1/1', '1/2', '1/3', '1/4', '1/5', '1/6', '1/7'],
            startDate: '01.01', // 格式化为 YYYY-MM-DD
            startTime: Math.floor(new Date().getTime() / 1000),
            endDate: '01.07',
            endTime: Math.floor(new Date().getTime() / 1000),
            note: '01.1-01.07'
        },
        sugarLowLabel: 3.9,
        sugarHighLabel: 10,
        sugarChart: {
            onInit: initSugarChart
        },
        foodChart: {
            onInit: initFoodChart
        },
        sportChart: {
            onInit: initSportChart
        },
        showedModel: "sugar",
        sugarData: {
            dateData: {},
            sumTimes: 2,
            normalTimes: 1,
            highTimes: 1,
            lowTimes: 0,
        },
        foodData: {
            dateData: {},
            sumTimes: 7,
            threeTimes: 3,
            twoTimes: 3,
            oneTimes: 1,
            snackTimes: 3
        },
        sportData: {
            highestHeartRate: [],
            lowestHeartRate: [],

            sumTimes: 3,
            sumCalorie: 1197,
            deltaCalorie: 414,
            calibration: 6

        }
    },
    modelChange(e) {
        var model = e.currentTarget.dataset.model;
        this.setData({
            showedModel: model
        })
    },
    getBloodSugarData() {
        wx.request({
            url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/user?Action=Report`,
            method: 'POST',
            header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token'),
            },
            data: {
                end_time: this.data.timeData.endTime
            },
            success: (res) => {
                console.log(res)
                if (res.data.code == 200) {
                    var message = res.data.message;
                    this.setData({
                        'sugarData.dateData': message.average.map(row => row.map(num => parseFloat(num.toFixed(1)))), // 对二维数组的每个数字保留两位小数
                        'sugarData.normalTimes': parseFloat(message.normal.toFixed(1)), // 保留1位小数
                        'sugarData.highTimes': parseFloat(message.high.toFixed(1)), // 保留1位小数
                        'sugarData.lowTimes': parseFloat(message.low.toFixed(1)), // 保留1位小数
                        'sugarData.sumTimes': parseFloat(message.total.toFixed(1)) // 保留1位小数
                    });

                    sugarChartData[0].value = parseFloat(message.normal.toFixed(1));
                    sugarChartData[1].value = parseFloat(message.high.toFixed(1));
                    sugarChartData[2].value = parseFloat(message.low.toFixed(1));
                    sugarChart.setOption(sugarChartOption, true);


                }
            }
        })
    },
    getFoodData() {
        wx.request({
            url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/diet?Action=Report`,
            method: 'POST',
            header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token'),
            },
            data: {
                end_time: this.data.timeData.endTime
            },
            success: (res) => {
                console.log(res)
                if (res.data.code == 200) {
                    var diets = res.data.message.diets;
                    var sumTimes = 0;
                    var threeTimes = 0;
                    var twoTimes = 0;
                    var oneTimes = 0;
                    var snackTimes = 0;
                    var breakfastList = [],
                        lunchList = [],
                        dinnerList = [],
                        snackList = [];
                    var proteinList = [],
                        cbdList = [],
                        fatList = [];
                    for (var diet of diets) {
                        var times = 0;
                        breakfastList.push(diet.breakfast);
                        lunchList.push(diet.lunch);
                        dinnerList.push(diet.dinner);
                        snackList.push(diet.snack);

                        proteinList.push(diet.protein);
                        cbdList.push(diet.cbd);
                        fatList.push(diet.fat);

                        times = diet.breakfast + diet.lunch + diet.dinner;
                        if (times > 0)
                            sumTimes += 1;
                        switch (times) {
                            case 1:
                                oneTimes += 1;
                                break;
                            case 2:
                                twoTimes += 1;
                                break;
                            case 3:
                                threeTimes += 1;
                                break;
                            default:
                                break;
                        }
                        snackTimes += diet.snack;
                    }
                    var dateData = {
                        'breakfast': breakfastList,
                        'lunch': lunchList,
                        'dinner': dinnerList,
                        'snack': snackList,
                    }
                    this.setData({
                        'foodData.dateData': dateData,
                        'foodData.sumTimes': sumTimes,
                        'foodData.threeTimes': threeTimes,
                        'foodData.twoTimes': twoTimes,
                        'foodData.oneTimes': oneTimes,
                        'foodData.snackTimes': snackTimes,
                    })

                    foodChartData.protein = proteinList;
                    foodChartData.cbd = cbdList;
                    foodChartData.fat = fatList;
                    foodChartOption.series[0].data = foodChartData.protein;
                    foodChartOption.series[1].data = foodChartData.cbd;
                    foodChartOption.series[2].data = foodChartData.fat;
                    foodChartOption.xAxis.data=foodChartData.date;
                    foodChart.setOption(foodChartOption, true);


                }
            }
        })
    },
    getSportData() {
        wx.request({
            url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/sport?Action=Report`,
            method: 'POST',
            header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token'),
            },
            data: {
                end_time: this.data.timeData.endTime
            },
            success: (res) => {
                console.log(res)
                if (res.data.code == 200) {
                    var hearts = res.data.message.hearts;
                    var averageList = [],
                        highestList = [],
                        lowestList = [];
                    for (var heart of hearts) {
                        averageList.push(heart.average);
                        highestList.push(heart.highest);
                        lowestList.push(heart.lowest);

                    }
                    this.setData({
                        'sportData.highestHeartRate': highestList,
                        'sportData.lowestHeartRate': lowestList,
                    });

                    sportChartData.value = averageList;
                    sportChartOption.series[0].data = sportChartData.value;
                    sportChartOption.xAxis.data=sportChartData.date;
                    sportChart.setOption(sportChartOption, true);


                }
            }
        })
    },

    getCalorieData() {
        wx.request({
            url: `${app.globalData.protocol}://${app.globalData.host}/bgmp/api/sport?Action=ReportCalorie`,
            method: 'POST',
            header: {
                "Content-Type": "application/json",
                "x-api-key": wx.getStorageSync('token'),
            },
            data: {
                end_time: this.data.timeData.endTime
            },
            success: (res) => {
                console.log(res)
                if (res.data.code == 200) {
                    var message = res.data.message;
                    this.setData({
                        'sportData.sumTimes': message.days,
                        'sportData.sumCalorie': message.calorie,
                        'sportData.deltaCalorie': Math.abs(message.change),
                        'sportData.deltaText': message.change>=0?'增加':'减少',                        'sportData.calibration': message.chick_leg
                    });

                }
            }
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var data = JSON.parse(options.data)
        var dateObj = new Date(data.startTime * 1000);
        var dates = []
        for (var i = 0; i < 7; i++) {
            var month = dateObj.getMonth() + 1;
            var date = dateObj.getDate();
            dates.push(month.toString() + '/' + date.toString())
            dateObj.setDate(dateObj.getDate() + 1);
        }
        data.dates = dates;
        foodChartData.date = dates
        sportChartData.date = dates
        this.setData({
            timeData: data
        })
        console.log(this.data.timeData)
        this.getBloodSugarData();
        this.getFoodData();
        this.getSportData();
        this.getCalorieData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})